'use strict';

const urlJoin = require('url-join');
const axios = require('axios');
const semver = require('semver')

const getDefaultRegister = (isOriginal = false) => {
    return isOriginal ? 'https://registry.npmjs.org/' : 'http://registry.npm.taobao.org/'
}


const getNpmInfo = (versionName, register) => {
    if(!versionName) {
        return null
    }
    const registerUrl = register || getDefaultRegister();
    const url = urlJoin(registerUrl, versionName);
    return axios.get(url).then(res => {
        if(res.status === 200) {
            return res.data
        }
        return null
    }).catch(e => {
        throw Promise.reject(e)
    })
}

const getNpmVersions = async (npmName, register) => {
    const data = await getNpmInfo(npmName, register);
    if(data) {
        return Object.keys(data.versions);
    }
    return []
}

const getSemverVersions = (baseVersion, versions) => {
    return versions.filter(version => semver.satisfies(version, `^${baseVersion}`)).sort((a , b) => semver.gt(b , a))
}

const getNpmSemverVersion = async (baseVersion, npmName, register) => {
    const versions = await getNpmVersions(npmName, register);
    const newVersions = getSemverVersions(baseVersion, versions);
    if(newVersions && newVersions.length) {
        return newVersions[0]
    } 
    return null;
}


module.exports = {getNpmInfo, getNpmSemverVersion};
